// src/routes/index.tsx
import React, { lazy, Suspense, FC } from "react";
import { useRoutes } from "react-router-dom";
import { HomeOutlined, ShopOutlined, UserOutlined } from "@ant-design/icons";
import type { XRoutes } from "./types";

import {
  Layout,
  EmptyLayout,
} from "../layouts";
import Loading from "@comps/Loading";
import Redirect from "@comps/Redirect";

const Login = lazy(() => import("@pages/login"));
const Dashboard = lazy(() => import("@pages/dashboard"));
const NotFound = lazy(() => import("@pages/404"));
const Premission = lazy(() => import("@pages/acl/permission"));
const Role = lazy(() => import("@pages/acl/role"));
const User = lazy(() => import("@pages/acl/user"));
const Attr = lazy(() => import("@pages/product/attr"));
const Sku = lazy(() => import("@pages/product/sku"));
const Spu = lazy(() => import("@pages/product/spu"));
const Trademark = lazy(() => import("@pages/product/trademark"));


const load = (Comp: FC) => {
  return (
    // 因为路由懒加载，组件需要一段网络请求时间才能加载并渲染
    // 在组件还未渲染时，fallback就生效，来渲染一个加载进度条效果
    // 当组件渲染完成时，fallback就失效了
    <Suspense fallback={<Loading />}>
      {/* 所有lazy的组件必须包裹Suspense组件，才能实现功能 */}
      <Comp />
    </Suspense>
  );
};
const AllAsyncRoutes: XRoutes = [
  {
    name: 'Acl',
    path: "/react/acl",
    meta: { icon: <UserOutlined />, title: "权限管理" },
    element: load(User),
    children: [
      {
        name: 'User',
        path: "/react/acl/user",
        meta: { title: "用户管理" },
        element: load(User),
      },
      {
        name: 'User',
        path: "/react/acl/role",
        meta: { title: "角色管理" },
        element: load(Role),
      },
      {
        name: 'User',
        path: "/react/acl/permission",
        meta: { title: "菜单管理" },
        element: load(Premission),
      },
    ]
  },
  {
    name: 'Product',
    path: "/react/product",
    meta: { icon: <ShopOutlined />, title: "商品管理" },
    element: load(Trademark),
    children: [
      {
        name: 'Trademark',
        path: "/react/product/trademark",
        meta: { title: "品牌管理" },
        element: load(Trademark),
      },
      {
        name: 'Attr',
        path: "/react/product/attr",
        meta: { title: "平台属性管理" },
        element: load(Attr),
      },
      {
        name: 'Spu',
        path: "/react/product/spu",
        meta: { title: "SPU管理" },
        element: load(Spu),
      },
      {
        name: 'Sku',
        path: "/react/product/sku",
        meta: { title: "SKU管理" },
        element: load(Sku),
      },
    ]
  },
]
const routes: XRoutes = [
  {
    path: "/",
    element: <EmptyLayout />,
    children: [
      {
        path: "login",
        element: load(Login),
      },
    ],
  },
  {
    path: "/react",
    element: <Layout />,
    children: [
      {
        name: 'Home',
        path: "/react/home",
        meta: { icon: <HomeOutlined />, title: "首页" },
        element: load(Dashboard),
      },
    ],
  },

  {
    path: "/404",
    element: load(NotFound),
  },
  {
    path: "*",
    element: <Redirect to="/404" />,
  },
];

// 渲染路由
// 注意：首字母必须大写
export const RenderRoutes = () => {
  // react-router-dom的新增语法。不用自己遍历了，它帮我们遍历生成
  const result = JSON.parse(localStorage.getItem('routes') as string) || []
  // const result = useAppSelector(selectUser).routes
  const result1 = [...result]
  const findUserAsyncRoutes = (allAsyncRoutes: any, routes: any): XRoutes => {
    return allAsyncRoutes.filter((item: any) => {
      if (routes.indexOf(item.name as string) !== -1) {
        if (item.children && item.children.length > 0) {
          item.children = findUserAsyncRoutes(item.children, routes)
        }
        return true
      }
    })
  }
  const data = findUserAsyncRoutes(AllAsyncRoutes, result1)
  // console.log(data)
  // if(data){
  //   routes[1].children.push(...data)
  // }
  // console.log(routes)
  let rou: any = []
  routes.forEach((item) => {
    if (item.path === '/react') {
      rou = Array.from(new Set(item.children))
      data.forEach(val => {
        // console.log(val)
        item.children?.forEach(res => {
          // console.log(res)
          if (val.name !== res.name && res.name !== 'Acl') {
            item.children?.push(val)
          }
        })
      })
    }
  })
  if (rou.length > 1) {
    for (var i = 0; i < 2; i++) {
      routes[1].children = rou
    }
  }

  // console.log(result)
  return useRoutes(routes);
};

// 找到要渲染成左侧菜单的路由
export const findSideBarRoutes = () => {
  const currentIndex = routes.findIndex((route) => route.path === "/react");
  return routes[currentIndex].children as XRoutes;
};

export default routes;
